<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>单张图片上传</title>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/js/layui/css/layui.css" media="all">
    <style>
        .layui-upload-img{width: 105px; height: 105px; margin: 0 10px 10px 0;}
    </style>
</head>
<body>

<div class="layui-upload">
    <button type="button" class="layui-btn" id="test1">
        <i class="layui-icon">&#xe67c;</i>上传图片
    </button>
    <div class="layui-upload-list">
        <img class="layui-upload-img" id="demo1" >
        <p id="demoText"></p>
    </div>
    <button type="button" class="layui-btn" id="test9">开始上传</button>
</div>
</body>

<script src="${pageContext.request.contextPath}/js/layui/layui.js"></script>
<script>
    var goId = 2;

    layui.use('upload', function(){
        var $ = layui.jquery
            ,upload = layui.upload;

        //普通图片上传
        var uploadInst = upload.render({
            elem: '#test1'
            ,url: '/goods/insertGoodsImg'   //改成您自己的上传接口
            ,auto: false					//选择文件后不自动上传
            ,bindAction: '#test9' 			// 指向一个按钮触发上传 (id)
            ,choose: function(obj){			//选择图片后做的事
                //预读本地文件示例，不支持ie8
                obj.preview(function(index, file, result){
                    $('#demo1').attr('src', result); //图片链接（base64）
                });
            }
            ,before: function(obj){
                this.data={"goId":goId,"type":"1"}//携带参数
            }
            ,done: function(res){       //上传后的回调函数
                if(res.code == 1001){   //上传成功
                    return layer.msg(res.message);
                }else if(res.code == 1002) {   //如果上传失败
                    return layer.msg(res.message);
                }

            }
            ,error: function(){
                //演示失败状态，并实现重传
                var demoText = $('#demoText');
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function(){
                    uploadInst.upload();
                });
            }
        });


    });
</script>

</html>
